import dva from 'dva';
import createLoading from 'dva-loading';
import { Router, Route, IndexRedirect } from 'dva/router';
import { useRouterHistory } from 'dva/router';
import { createHashHistory } from 'history';
import { addRoute, getRoutes } from '../framework/config/RouteHolder';
import { ToastTips } from '../common/toastTips/tosat';
import framework from '../framework/index';
import main from '../main/index';
import './index.css';

import token from '../framework/utils/token';

const weChatToken = window.C.accessToken;
let indexUrl = '/part-time';
// if(weChatToken){
//   token.save(window.C.accessToken);
//   indexUrl = '/part-time';
// }else{
//   let hasToken = token.get();
//   let loginUrl = window.document.location.origin + '/register.html#/login'
//   if(hasToken){
//     indexUrl = '/part-time';
//   }else{
//     window.location.href = loginUrl;
//   }
// }
//end

// 1. Initialize
const app = dva({
  history: useRouterHistory(createHashHistory)({ queryKey: false }),
  onError(e) {
    console.log(e);
    if (e instanceof TypeError && e.message === 'Type error' && e.response === undefined) {
      window.location.href = window.location.pathname + "#/error";
    }
    console.log('e.response.status', JSON.stringify(e.response.status));
    if(e.response.status == 401){
      // ToastTips('需要先登录后才能操作该功能');
      window.location.href = window.document.location.origin + '/register.html#/login';
    }

    console.log("ERROR ", JSON.stringify(e), e.message, e.response);

    if (e.response.status === 400 || e.response.status === 403) {
     e.response.json().then((res) => {
       if (res) {
         const msg = [];
         msg.push(res.message);
         if (res.errors && res.errors.length > 0) {
           msg.push(JSON.stringify(res.errors[0]));
         }
         ToastTips(msg.join(", "));
         console.log("ERROR MESSAGE", JSON.stringify(msg));
       }
     });
    }
  }
});

framework.init(app, {
  demo: false,
});

main.init(app);

// 2. Plugins
// app.use({});
app.use(createLoading());


addRoute({
  path: '/index',
  name: '/index',
  indexRoute: { onEnter: (nextState, replace) => replace(indexUrl) }
});

app.router(({ history }) => {
  return (
    <Router history={history} routes={getRoutes()} />
  )
});

app.start('#root');
